<?php
namespace common\models\group;

use common\models\circle\CircleComment;
use common\models\circle\CircleCommentAtRelation;
use common\models\circle\CircleUserRelation;
use common\models\Common;
use common\models\friend\FriendApply;
use common\models\im\Im;
use common\models\Status;
use common\models\user\User;
use common\models\user\UserAttention;
use common\models\user\UserGreet;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class GroupUser extends Common
{

    public static function tableName()
    {
        return '{{%group_user}}'; // TODO: Change the autogenerated stub
    }


    public function getGroup()
    {
        return $this->hasOne(Group::className(), ['id' => 'group_id']);
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getInviteUser()
    {
        return $this->hasOne(User::className(), ['id' => 'invite_user_id']);
    }

    public function getUserApplyCount() {
        return $this->hasOne(FriendApply::className(), ['friend_id' => 'user_id'])->onCondition(['status' => Status::COMMON_CHECKING_WAITING]);
    }

    public function getGroupApplyInviteCount() {
        return $this->hasOne(GroupApply::className(), ['group_id' => 'group_id'])->onCondition([
            'status' => Status::COMMON_CHECKING_WAITING,
            'be_invited_status' => Status::COMMON_CHECKING_SUCCESS
        ]);
    }

    public function getGroupBeApplyInviteCount() {
        return $this->hasOne(GroupApply::className(), ['user_id' => 'user_id'])->onCondition(['be_invited_status' => Status::COMMON_CHECKING_WAITING]);
    }

    // 圈子被点赞数量
    public function getCircleLikeCount() {
        return $this->hasOne(CircleUserRelation::className(), ['topic_user_id' => 'user_id'])->onCondition([
            'type' => Status::CIRCLE_USER_RELATION_TYPE_LIKE,
            'is_read' => Status::COMMON_RADIO_NO,
        ]);
    }

    // 圈子被收藏数量
    public function getCircleCollectCount() {
        return $this->hasOne(CircleUserRelation::className(), ['topic_user_id' => 'user_id'])->onCondition([
            'type' => Status::CIRCLE_USER_RELATION_TYPE_COLLECT,
            'is_read' => Status::COMMON_RADIO_NO,
        ]);
    }

    // 新增关注的数量
    public function getAttentionCount() {
        return $this->hasOne(UserAttention::className(), ['topic_id' => 'user_id'])->onCondition([
            'is_read' => Status::COMMON_RADIO_NO,
        ]);
    }


    // 评论数量
    public function getCommentCount() {
        return $this->hasOne(CircleComment::className(), ['topic_user_id' => 'user_id'])->onCondition([
            'is_read' => Status::COMMON_RADIO_NO,
        ]);
    }

    // 评论@数量
    public function getCommentAtCount() {
        return $this->hasOne(CircleCommentAtRelation::className(), ['topic_user_id' => 'user_id'])->onCondition([
            'is_read' => Status::COMMON_RADIO_NO,
        ]);
    }

    // 打招呼数量
    public function getGreetCount() {
        return $this->hasOne(UserGreet::className(), ['greet_user_id' => 'user_id'])->onCondition([
            'is_read' => Status::COMMON_RADIO_NO,
        ]);
    }

    /**
     * 用户退群
     * @param int $groupUserId
     * @param int $userId
     * @param string $userTxCode
     * @param string $userNickName
     * @param int $groupId
     * @param string $groupTxCode
     * @return bool
     * @throws Exception
     */
    public function quitGroupUser($groupUserId = 0, $userId = 0, $userTxCode = '', $userNickName = "", $groupId = 0, $groupTxCode = '') {

        if (!$groupTxCode) {
            return true;
        }

        // 群成员信息  与  群申请信息全都删除
        $resGroupUserDel = static::deleteAll(['id' => $groupUserId]);
        if ($resGroupUserDel === false) {
            throw new Exception('退群失败1！');
        }

        $resGroupApplyDel = GroupApply::deleteAll([
            'group_id' => $groupId,
            'user_id' => $userId,
        ]);
        if ($resGroupApplyDel === false) {
            throw new Exception('退群失败2！');
        }

        // im退群
        $delImGroupUserData['GroupId'] = $groupTxCode;
        $delImGroupUserData['Silence'] = 1; # 当 Silence 为1时，成员成功删除后，不会给任何人下发系统通知。
        $delImGroupUserData['MemberToDel_Account'] = [
            $userTxCode,
        ];

        $resDelImGroupUserData = (new Im()) -> delGroupUser($delImGroupUserData);
//            if (!$resDelImGroupUserData ) {
//                throw new Exception('退群失败3！');
//            }

        // 修改群头像
//            (new Group()) -> _updateGroupPic($groupId);

        // 发送im消息
        $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
        $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_QUIT_GROUP;  // 主动退出群聊
        $publicGroupMessage['oneTxCode'] = $userTxCode;
        $publicGroupMessage['oneNIckName'] = $userNickName;
        $publicGroupMessage['content'] = $userNickName."已退出群聊！";
        (new Im())->sendGroupMessage($groupTxCode, $publicGroupMessage);
    }


}
